package org.darcy.controller.admin.site;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.darcy.entity.BizPage;
import org.darcy.framework.blog.business.enums.ResponseStatus;
import org.darcy.framework.model.PageResult;
import org.darcy.framework.model.ResponseVO;
import org.darcy.framework.util.ResultUtil;
import org.darcy.model.BizPageModel;
import org.darcy.service.BizPageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import cn.hutool.core.util.StrUtil;

/**
 * 自定义页面
 */
@RestController
@RequestMapping("/page")
public class PageController {

	@Autowired
	private BizPageService bizPageService;

	@RequiresPermissions("page")
	@PostMapping("/list")
	public PageResult list(BizPageModel param) {
		Page p = new Page(param.getP(), param.getPageSize());
		QueryWrapper<BizPage> q = new QueryWrapper<BizPage>();
		if (StrUtil.isNotEmpty(param.getUrl()))
			q.like("url", param.getUrl());
		IPage pageInfo = bizPageService.getPage(p, q);
		return ResultUtil.tablePage(pageInfo);
	}

	@RequiresPermissions("page:add")
	@PostMapping(value = "/add")
	public ResponseVO add(BizPage page) {
		BizPage dbPage = bizPageService.getByUrl(page.getUrl());
		if (dbPage != null) {
			return ResultUtil.error(page.getUrl() + " 已存在！");
		}
		bizPageService.insert(page);
		return ResultUtil.success("成功");
	}

	@RequiresPermissions(value = { "page:batchDelete", "page:delete" }, logical = Logical.OR)
	@PostMapping(value = "/remove")
	public ResponseVO remove(Long[] ids) {
		if (null == ids) {
			return ResultUtil.error(500, "请至少选择一条记录");
		}
		for (Long id : ids) {
			bizPageService.delete(id);
		}
		return ResultUtil.success("成功删除 [" + ids.length + "] 条记录");
	}

	@RequiresPermissions("page:edit")
	@PostMapping("/get/{id}")
	public ResponseVO get(@PathVariable Long id) {
		return ResultUtil.success(null, this.bizPageService.getById(id));
	}

	@RequiresPermissions("page:edit")
	@PostMapping("/edit")
	public ResponseVO edit(BizPage page) {
		try {
			BizPage dbPage = bizPageService.getById(page.getId());
			if (null != dbPage && !dbPage.getUrl().equals(page.getUrl())) {
				dbPage = bizPageService.getByUrl(page.getUrl());
				if (dbPage != null) {
					return ResultUtil.error(page.getUrl() + " 已存在！");
				}
			}
			bizPageService.update(page);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultUtil.error("数据修改失败！");
		}
		return ResultUtil.success(ResponseStatus.SUCCESS);
	}

}
